<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span {
            color: red
        }

        input {
            border: solid 1px #ccc;
            outline: none;
        }
    </style>
</head>

<body>
    <!-- https://passport.baidu.com/v2/?reg&tt=1588820377139&overseas=undefined&gid=69F7DA9-E326-44C9-B037-039A3149582A&tpl=mn&u=https%3A%2F%2Fwww.baidu.com%2F%3Ftn%3D62095104_26_oem_dg -->
    <p><input type="text" id="u"><span id="us"></span></p>
    <p><input type="password" id="p"><span id="ps"></span></p>
    <button onclick="checkLogin()">登录</button>
    <script>
        var u = document.querySelector('#u');
        var us = document.querySelector('#us');
        var p = document.querySelector('#p');
        var ps = document.querySelector('#ps');
        // 用户名验证
        u.onfocus = function () {
            u.style.borderColor = 'blue';
            us.innerHTML = '';
        }
        u.onblur = function () {
            if (u.value == '') {
                u.style.borderColor = 'red';
                us.innerHTML = '用户名必须填写'
            } else {
                u.style.borderColor = '#ccc';
            }
        }
        p.onfocus = function () { // 密码框获取焦点是验证
            p.style.borderColor = 'blue';
            ps.innerHTML = '';
        }
        p.onblur = function () {
            if (p.value == '') {  // 可以将此判断交给else if
                p.style.borderColor = 'red';
                ps.innerHTML = '密码必须填写'
            } else if (p.value.length > 16 || p.value.length < 6) {
                p.style.borderColor = 'red';
                ps.innerHTML = '密码长度必须是6~16位'
            } else {
                p.style.borderColor = '#ccc';
            }
        }



        function checkLogin() {
            if (u.value == '') {
                us.innerText = '用户名不能为空';
            } else if (p.value == '') {
                ps.innerText = '密码不能为空';
            } else {
                alert('验证通过');
            }
        }
    </script>
</body>

</html>